package com.yixiang.np.logaop;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.yixiang.np.constant.Constant;
import com.yixiang.np.utils.DateUtil;

@Aspect
@Component
public class RequestLimitContract {
    private static final Logger logger = LoggerFactory.getLogger("RequestLimitLogger");

    @Before("within(@org.springframework.stereotype.Controller *) && @annotation(limit)")
    public void requestLimit(final JoinPoint joinPoint, RequestLimit limit) throws RequestLimitException {

      try {
            Object[] args = joinPoint.getArgs();
            HttpServletRequest request = null;
            for (int i = 0; i < args.length; i++) {
                if (args[i] instanceof HttpServletRequest) {
                    request = (HttpServletRequest) args[i];
                    break;
                }
            }
            if (request == null) {
                throw new RequestLimitException("方法中缺失HttpServletRequest参数");
            }
            String ip = request.getRemoteAddr();
            String url = request.getRequestURL().toString();
            if(!Constant.ipMap.containsKey(ip)){
            	Constant.ipMap.put(ip, 1);
            	Constant.ipTimeMap.put(ip, new Date());
            }else{
            	//检查时间限制范围内当前IP的访问量是否超出设定范围
            	int count = Constant.ipMap.get(ip);
            	Date begin = Constant.ipTimeMap.get(ip);
            	Date end = new Date();
            	long between = end.getTime()-begin.getTime();//毫秒数
            	if(between >= limit.time()){
            		Constant.ipMap.put(ip, 1);
                	Constant.ipTimeMap.put(ip, new Date());
            	}else{
            		if (count > limit.count()) {
                        logger.info("用户IP[" + ip + "]访问地址[" + url + "]超过了限定的次数[" + limit.count() + "]");
                        throw new RequestLimitException();
                    }else{
                    	Constant.ipMap.put(ip, count+1);
                    }
            	}
            }
        } catch (RequestLimitException e) {
            throw e;
        } catch (Exception e) {
            logger.error("发生异常: ", e);
        }
    }
}